import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/servers/question_list.dart';
import 'package:interview/utils/logger.dart';


class QuestionPageState {
  final RxList<Question> questionList = <Question>[].obs; // 每个 typeId 的问题列表
  final RxBool isFinished = false.obs; // 是否加载完成
  final RxBool isLoading = false.obs; // 是否正在加载中
  int currentPage = 1; // 当前页码
  int pageTotal = 1; // 总页数

  void reset() {
    questionList.clear();
    isFinished.value = false;
    currentPage = 1;
  }
}

class QuestionController extends GetxController {
  final RxMap<int, QuestionPageState> pageStateMap = <int, QuestionPageState>{}.obs; // typeId -> PageState

  // keyword -> PageState 的映射
  final RxMap<String, QuestionPageState> keywordPageStateMap = <String, QuestionPageState>{}.obs;

  // 获取某个 typeId 的状态
  QuestionPageState getPageState(int typeId) {
    pageStateMap.putIfAbsent(typeId, () => QuestionPageState());
    return pageStateMap[typeId]!;
  }

    // 获取某个 keyword 的状态
  QuestionPageState getKeywordPageState(String keyword) {
    if (keyword.isEmpty) throw ArgumentError("keyword 不能为空");
    keywordPageStateMap.putIfAbsent(keyword, () => QuestionPageState());
    return keywordPageStateMap[keyword]!;
  }

  // 刷新数据（支持 typeId 或 keyword）
  Future<void> refreshQuestions({
    required BuildContext context,
    int? typeId,
    int? sort,
    String? keyword,
  }) async {
    final state = keyword != null? getKeywordPageState(keyword): getPageState(typeId!);
    if (state.isLoading.value) return;
    state.isLoading.value = true;
    state.reset();
    // 调用通用的 fetch 方法
    await _fetchQuestions(
      context: context,
      typeId: typeId,
      sort: sort,
      keyword: keyword,
      state: state,
    );
    state.isLoading.value = false;
  }

  // 加载更多数据（支持 typeId 或 keyword）
  Future<void> loadMoreQuestions({
    required BuildContext context,
    int? typeId,
    int? sort,
    String? keyword,
  }) async {
    final state = keyword != null ? getKeywordPageState(keyword) : getPageState(typeId!);

    if (state.isLoading.value || state.isFinished.value) return;

    state.isLoading.value = true;

    // 调用通用的 fetch 方法
    await _fetchQuestions(
      context: context,
      typeId: typeId,
      sort: sort,
      keyword: keyword,
      state: state,
    );

    state.isLoading.value = false;
  }

  // 通用的请求方法
  Future<void> _fetchQuestions({
    required BuildContext context,
    int? typeId,
    int? sort,
    String? keyword,
    required QuestionPageState state,
  }) async {
    try {
      // 构造请求参数
      final params = keyword != null
        ? QuestionListParams(keyword: keyword, questionBankType: 10 , page: state.currentPage, pageSize: 10)
        : QuestionListParams(type: typeId,sort: sort,questionBankType: 10,page: state.currentPage, pageSize: 10,);
      // 发起请求
      final result = await fetchQuestionList(params, context);

      // 处理结果
      if (result.questions.isNotEmpty) {
        state.questionList.addAll(result.questions);
        state.pageTotal = result.pageTotal;
        state.currentPage++;
        state.isFinished.value = state.currentPage > state.pageTotal;
      } else {
        state.isFinished.value = true;
      }
    } catch (e) {
      Logger.error("加载试题失败: $e", tag: "fetchQuestions");
    }
  }


  // 同步详情页点赞数量
  void toggleLikeCount(int typeId, String id, RxInt newLikeCount) {
    try {
      final state = getPageState(typeId);
      final question = state.questionList.firstWhere((item) => item.id == id);
      question.likeCount.value = newLikeCount.value;
      state.questionList.refresh();
    } catch (e) {
      Logger.error("同步详情页点赞数量: $e", tag: "toggleLikeCount");
      rethrow; // 抛出错误
    }
  }

  // 同步详情页浏览量
  void toggleViews(int typeId, String id, RxInt newViews){
     try {
      final state = getPageState(typeId);
      final question = state.questionList.firstWhere((item) => item.id == id);
      question.views.value = newViews.value;
      state.questionList.refresh();
    } catch (e) {
      Logger.error("同步详情页浏览量: $e", tag: "toggleLikeCount");
      rethrow; // 抛出错误
    }
  }
}